package org.server.http;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.server.http.conf.BlockedIpConfig;
import org.server.http.conf.ServerConfig;
import org.task.queue.concurrent.ConcurrentDequeAssigner;

/**
 * 嵌入式运行
 * 
 * @author Admin
 * 
 */
public class EmbeddedRunner {
	// 阻止ip
	private final static BlockedIpConfig blocked_ip = BlockedIpConfig.getInstance();

	// private final static Logger log = Logger.getLogger("http-server");

	/**
	 * 嵌入式运行
	 */
	public static void startup() {
		new RunnerHttpServer().start();
	}

	// 启动一个线程执行，避免造成调用程序被阻塞
	static class RunnerHttpServer extends Thread {
		public void run() {
			// 构建一个线程池
			ConcurrentDequeAssigner concurr = new ConcurrentDequeAssigner(ServerConfig.getThreadSize(),
					ServerConfig.getThreadSize());
			// 构建服务器，监听端口
			ServerSocket server = null;
			try {
				server = new ServerSocket(ServerConfig.getPort());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while (true) {
				try {
					Socket sock = server.accept();
					String ip = sock.getInetAddress().getHostAddress();
					// log.info(ip + "\t" + new Date().toString());
					if (blocked_ip.isBlocked(ip)) {
						// ip被禁，直接关闭
						sock.close();
					} else {
						try {
							// 添加到线程池
							concurr.put(new SchedHandler(sock));
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
